// const express = require('express');
import express from "express"
// const path=require('path')
import path from "path"
import mysqlCon from "../mysql/init.js"
import { __dirname,handlerSuccess,handlerError } from "../utils/share.js"
import { ERROR_USER_01,ERROR_USER_02,USER_SUCCESS,USER_COMM_ERROR} from "../constant/user.js"
const router = express.Router();
// 获取所有用户
/*
req {
    params:{} //  # /get/{id}   req.params.id
    body:{}
    query:{},//   # /get?id=  req.query.id
}
*/
router.get('/', async (req, res) => {
    //, DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') as create_time , DATE_FORMAT(update_time, '%Y-%m-%d %H:%i:%s') as update_time
    mysqlCon.query("select * from user",(err, results)=>{
        if(!err){
            const data=handlerSuccess(results,'list')
            data['results']=results
            res.json(data)
        }else{
            res.json(handlerError(ERROR_USER_02,err))
        }
    })
});
router.get('/add', async (req, res) => {
    const { name,power,pass}=req.query
    const addSql = 'INSERT INTO user (user_name, userr_pass, power) VALUES (?, ?,  ?)';
    const addParams = [name||'chenfan', pass||'chenfan123456', power||'0'];
    mysqlCon.query("select id from user where user_name=?",[name||'chenfan'],(queryErr, queryRes)=>{
        if(!queryErr){
            if(queryRes.length){
                res.json(ERROR_USER_01)
            }else{
                mysqlCon.query(addSql,addParams,(err, results)=>{
                    if(!err){
                        const data=handlerSuccess(USER_SUCCESS)
                        res.json(data)
                    }else{
                        res.json(handlerError(USER_COMM_ERROR,err))
                    }
                })
            }
        }else{
            res.json(handlerError(USER_COMM_ERROR,err))
        }
    })
    
})
// 创建新用户
router.post('/update', async (req, res) => {
  res.json(handlerSuccess({"a":"save",__dirname}))
});

router.get('/html', async (req, res) => {
    //   res.redirect('/public/index.html')
    res.sendFile(path.join(__dirname, '/public/index.html'));
});

// 
// module.exports = router;
export default router